package com.neusoft.neu24.nep.role.myjwt;
import com.neusoft.neu24.nep.entity.Member;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class JwtService {

    private    static  final  String ID ="id";
    private    static  final  String NAME ="mname";
    private static final Object ROLEID = "roleid";
    private static final String LOGID = "logid" ;
    private  static   final  byte[] secretKey  =  "neusoft,123!neusoft,123!neusoft,123!".getBytes();



    public String generateToken(Member member) {
        Map map =new HashMap();
        map.put(  ID , member.getId()  );
        map.put(  ROLEID , member.getRoleid()  );
        map.put(  NAME , member.getMname()  );
        map.put(  LOGID , member.getLogid()  );
        return Jwts.builder()
                .setSubject("auth")
                .setClaims(map)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 3600*1000)) // 1 hour
                .signWith( SignatureAlgorithm.HS256 , secretKey )
                .compact();
    }

    public  Member parseToken(String token) {
//        如果Token被篡改，那么 以下语句异常
        Claims body = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
            Member member = new Member();
            member.setId( (Integer) body.get(ID) );
            member.setRoleid( (Integer) body.get(ROLEID) );
            member.setMname( (String) body.get(NAME) );
            member.setLogid( (String) body.get(LOGID) );
            return member;


    }





//
//    public  Member parseToken(String token) {
//        byte[] bs = new byte[3];
//        bs[0] =  -128;  //  1111 1111
//        bs[1] =  -128;
//        bs[2] =  -128;
////        1111 11 , 11  1111 , 1111  11 ,11 1111
////     ////
//        return   null;
//    }
}
